package com.hzmg.strategyfactory.factory;

import com.hzmg.strategyfactory.pojo.Parameter;
import com.hzmg.strategyfactory.service.PetStrategyService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工厂模式示例
 *
 * @author zbw
 */
@Component
public class PetStrategyServiceFactory implements ApplicationContextAware {
    /**
     * 存放对应的类型和实现类
     */
    private Map<String, PetStrategyService> map = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, PetStrategyService> tempMap = applicationContext.getBeansOfType(PetStrategyService.class);
        tempMap.values().forEach(petStrategyService -> map.put(petStrategyService.getType(), petStrategyService));
    }

    public String nameForThings(Parameter dto) {
        PetStrategyService petStrategyService = map.get(dto.getType());
        if (petStrategyService != null) {
            return petStrategyService.nameForThings(dto);
        }
        return null;
    }

}
